// ================================================
// Builder.Alyr.Net 智能体生成文件 [动态配置] [动态日期]
// (c) 2020-2025 ALYR.NET // 版权不可修改
// ================================================

const fs = require('fs');
const path = require('path');
const chalk = require('chalk');

/**
 * Builder.Alyr.Net 统一配置管理器
 * @class UnifiedConfigManager
 * @description 提供一键修改自动同步所有配置的功能
 */
class UnifiedConfigManager {
  constructor() {
    this.configPath = path.join(__dirname, 'unified-data-config.json');
    this.targetFiles = [
      // 配置文件
      '../package.json',
      '../package-lock.json',
      'unified-data-config.json',
      'unified-config-manager.js',
      'tech-stack-config.json',
      'directory-structure.json',
      'extended-frameworks-config.json',
      'package.json',
      'package-lock.json',
      'config-sync.js',
      
      // 主要文件
      '../start.js',
      '../.gitignore',
      '../README.md',
      
      // 批处理文件
      '../1. 安装依赖.bat',
      '../2. 项目设置.bat',
      '../3. 启动监测.bat',
      '../4. 卸载依赖.bat',
      
      // 核心文件
      '../core/start.js',
      '../core/system-health-check.js',
      '../core/real-time-monitor.js',
      '../core/fix-file.js',
      '../core/ai-rules-checker.js',
      '../core/auto-fix-helper.js',
      
      // 工具文件
      '../utils/version-info.js',
      '../utils/smart-install.js',
      '../utils/auto-setup.js',
      '../utils/ai-bootstrap.js',
      '../utils/unified-config-cli.js',
      '../utils/multi-framework-adapter.js',
      '../utils/code-generator-cli.js',
      '../utils/framework-selector.js',
      '../utils/git-force-sync.js',
      '../utils/one-click-setup.js',
      '../utils/install-report.json',
      
      // 文档文件
      '../docs/COMPLETE-USER-GUIDE.md',
      '../docs/PROJECT-OVERVIEW.md',
      '../docs/README.md',
      
      // 规则文件
      '../project_rules.md',
      '../user_rules.md',
      '../智能体执行检查清单.md'
    ];
    
    this.config = this.loadConfig();
    this.backupDir = path.join(__dirname, 'backups');
    this.ensureBackupDir();
  }

  /**
   * 加载统一配置
   */
  loadConfig() {
    try {
      if (fs.existsSync(this.configPath)) {
        const content = fs.readFileSync(this.configPath, 'utf8');
        return JSON.parse(content);
      }
      return this.getDefaultConfig();
    } catch (error) {
      console.log(chalk.red(`❌ 配置加载失败: ${error.message}`));
      return this.getDefaultConfig();
    }
  }

  /**
   * 获取默认配置
   */
  getDefaultConfig() {
    return {
      "meta": {
        "name": "Builder.Alyr.Net 统一配置数据",
        "version": "V4.2.3",
        "lastUpdated": new Date().toISOString(),
        "description": "一键修改自动同步所有配置的统一数据源",
        "author": "ALYR.NET",
        "copyright": "(c) 2020-2025 ALYR.NET"
      },
      
      "project": {
        "name": "builder-alyr-net",
        "displayName": "Builder.Alyr.Net 智能体代码规范检测工具",
        "version": "V4.2.3",
        "description": "Builder.Alyr.Net 智能体代码规范检测工具 Trae 版",
        "author": "ALYR.NET",
        "license": "MIT",
        "homepage": "https://gitee.com/Alyr_space/Builder.Alyr.Net",
        "repository": "https://gitee.com/Alyr_space/Builder.Alyr.Net.git",
        "nodeVersion": ">=14.0.0"
      },

      "languages": {
        "frontend": [
          {
            "name": "JavaScript",
            "key": "javascript",
            "extensions": [".js", ".jsx"],
            "description": "前端交互的核心语言",
            "popularity": "high",
            "frameworks": ["react", "vue", "angular", "svelte"],
            "enabled": true
          },
          {
            "name": "TypeScript",
            "key": "typescript", 
            "extensions": [".ts", ".tsx"],
            "description": "JavaScript的超集，增加静态类型",
            "popularity": "high",
            "frameworks": ["react", "vue", "angular", "nestjs"],
            "enabled": true
          },
          {
            "name": "HTML/CSS",
            "key": "html-css",
            "extensions": [".html", ".css", ".scss", ".less"],
            "description": "网页结构和样式的基础",
            "popularity": "essential",
            "frameworks": ["all"],
            "enabled": true
          }
        ],
        "backend": [
          {
            "name": "Java",
            "key": "java",
            "extensions": [".java"],
            "description": "企业级应用主流",
            "popularity": "high",
            "frameworks": ["spring-boot", "spring-cloud"],
            "enabled": true
          },
          {
            "name": "Python",
            "key": "python",
            "extensions": [".py"],
            "description": "简洁高效，适合AI/数据分析",
            "popularity": "high", 
            "frameworks": ["django", "flask", "fastapi"],
            "enabled": true
          },
          {
            "name": "Node.js",
            "key": "nodejs",
            "extensions": [".js", ".ts"],
            "description": "全栈开发",
            "popularity": "high",
            "frameworks": ["express", "nestjs", "koa"],
            "enabled": true
          },
          {
            "name": "Go",
            "key": "go",
            "extensions": [".go"],
            "description": "高并发、云原生首选",
            "popularity": "growing",
            "frameworks": ["gin", "fiber", "echo"],
            "enabled": true
          },
          {
            "name": "C#",
            "key": "csharp",
            "extensions": [".cs"],
            "description": ".NET生态，企业应用",
            "popularity": "high",
            "frameworks": ["asp-net-core", "blazor"],
            "enabled": true
          },
          {
            "name": "PHP",
            "key": "php",
            "extensions": [".php"],
            "description": "Web开发传统语言",
            "popularity": "stable",
            "frameworks": ["laravel", "symfony", "codeigniter"],
            "enabled": true
          },
          {
            "name": "Ruby",
            "key": "ruby",
            "extensions": [".rb"],
            "description": "以Rails框架闻名",
            "popularity": "stable",
            "frameworks": ["rails", "sinatra"],
            "enabled": true
          },
          {
            "name": "Rust",
            "key": "rust",
            "extensions": [".rs"],
            "description": "系统级语言，注重安全性能",
            "popularity": "growing",
            "frameworks": ["actix-web", "warp", "rocket"],
            "enabled": true
          }
        ]
      },

      "frameworks": {
        "frontend": [
          {
            "name": "React",
            "key": "react",
            "language": "javascript/typescript",
            "description": "组件化、虚拟DOM",
            "useCase": "复杂SPA，生态强大",
            "popularity": "high",
            "companies": ["Facebook", "Netflix", "Airbnb", "阿里巴巴"],
            "componentLibraries": ["ant-design", "material-ui", "chakra-ui"],
            "enabled": true
          },
          {
            "name": "Vue",
            "key": "vue",
            "language": "javascript/typescript",
            "description": "渐进式、易上手",
            "useCase": "中小型项目快速开发",
            "popularity": "high",
            "companies": ["腾讯", "饿了么", "GitLab"],
            "componentLibraries": ["element-plus", "ant-design-vue", "vuetify"],
            "enabled": true
          },
          {
            "name": "Angular",
            "key": "angular",
            "language": "typescript",
            "description": "全功能型框架（TypeScript）",
            "useCase": "大型企业级应用",
            "popularity": "medium",
            "companies": ["Google", "Microsoft", "Deutsche Bank"],
            "componentLibraries": ["angular-material", "ng-bootstrap"],
            "enabled": true
          },
          {
            "name": "Svelte",
            "key": "svelte",
            "language": "javascript/typescript",
            "description": "编译时框架，无虚拟DOM",
            "useCase": "高性能轻量级应用",
            "popularity": "growing",
            "companies": ["The New York Times", "Apple"],
            "componentLibraries": ["svelteui", "carbon-components-svelte"],
            "enabled": true
          }
        ],
        "backend": [
          {
            "name": "Spring Boot",
            "key": "spring-boot",
            "language": "java",
            "description": "一站式企业级解决方案",
            "useCase": "企业级微服务架构",
            "popularity": "high",
            "companies": ["阿里巴巴", "Netflix", "Pivotal"],
            "enabled": true
          },
          {
            "name": "Django",
            "key": "django",
            "language": "python",
            "description": "全功能ORM，开箱即用",
            "useCase": "快速Web开发",
            "popularity": "high",
            "companies": ["Instagram", "Pinterest", "Mozilla"],
            "enabled": true
          },
          {
            "name": "FastAPI",
            "key": "fastapi",
            "language": "python",
            "description": "现代、快速的Web框架",
            "useCase": "高性能API开发",
            "popularity": "growing",
            "companies": ["Microsoft", "Uber"],
            "enabled": true
          },
          {
            "name": "NestJS",
            "key": "nestjs",
            "language": "typescript",
            "description": "类Angular架构，TypeScript",
            "useCase": "企业级Node.js应用",
            "popularity": "growing",
            "companies": ["Adidas", "Roche"],
            "enabled": true
          },
          {
            "name": "Express",
            "key": "express",
            "language": "nodejs",
            "description": "最小化灵活框架",
            "useCase": "快速API开发",
            "popularity": "high",
            "companies": ["IBM", "Accenture"],
            "enabled": true
          },
          {
            "name": "Gin",
            "key": "gin",
            "language": "go",
            "description": "高性能HTTP Web框架",
            "useCase": "微服务和API开发",
            "popularity": "high",
            "companies": ["字节跳动", "滴滴"],
            "enabled": true
          }
        ],
        "mobile": [
          {
            "name": "React Native",
            "key": "react-native",
            "language": "javascript/typescript",
            "description": "跨平台移动应用开发",
            "useCase": "iOS/Android应用",
            "popularity": "high",
            "companies": ["Facebook", "Instagram", "Airbnb"],
            "enabled": true
          },
          {
            "name": "Flutter",
            "key": "flutter",
            "language": "dart",
            "description": "Google跨平台UI工具包",
            "useCase": "高性能移动应用",
            "popularity": "growing",
            "companies": ["Google", "阿里巴巴", "腾讯"],
            "enabled": true
          }
        ]
      },

      "dependencies": {
        "Node.js": {
          "files": ["package.json"],
          "commands": ["npm install", "yarn install"],
          "check": "npm --version"
        },
        "Python": {
          "files": ["requirements.txt", "pyproject.toml", "setup.py", "Pipfile"],
          "commands": ["pip install -r requirements.txt", "pipenv install", "poetry install"],
          "check": "python --version"
        },
        "Java": {
          "files": ["pom.xml", "build.gradle", "build.gradle.kts"],
          "commands": ["mvn install", "gradle build", "./gradlew build"],
          "check": "java -version"
        },
        "Go": {
          "files": ["go.mod", "go.sum"],
          "commands": ["go mod download", "go mod tidy"],
          "check": "go version"
        }
      },

      "developmentStandards": {
        "fileNaming": {
          "backend": {
            "prefix": "{动态前缀}-",
            "pattern": "{前缀}-{PascalCase}.{ext}",
            "examples": ["{前缀}-Service.ts", "{前缀}-Controller.ts"],
            "enforcement": "strict",
            "violation": "delete",
            "note": "前缀可通过一键项目设置.bat步骤8修改，默认为Alyr"
          },
          "frontend": {
            "pattern": "{kebab-case}.{ext}",
            "examples": ["user-list.tsx", "auth-form.tsx"],
            "enforcement": "warning",
            "violation": "warn"
          }
        },
        "copyright": {
          "template": "© 2020-2025 ALYR.NET",
          "fileHeader": "// Builder.Alyr.Net 智能体生成文件 [Builder.Alyr.Net] [${date}]",
          "backend": {
            "required": true,
            "enforcement": "strict",
            "violation": "block"
          },
          "frontend": {
            "required": false,
            "enforcement": "optional"
          }
        },
        "componentLibraries": {
          "frontend": {
            "react": {
              "primary": "ProComponents",
              "components": ["ProTable", "ProForm", "ProLayout"],
              "forbidden": ["原生 AntD 组件"],
              "enforcement": "strict",
              "violation": "compile_fail"
            },
            "vue": {
              "primary": "Element Plus",
              "components": ["el-table", "el-form", "el-layout"],
              "alternatives": ["Ant Design Vue", "Vuetify"]
            },
            "angular": {
              "primary": "Angular Material",
              "components": ["mat-table", "mat-form", "mat-layout"],
              "alternatives": ["ng-bootstrap"]
            }
          }
        },
        "chartLibraries": {
          "allowed": ["AntV/G2Plot"],
          "forbidden": ["Echarts"],
          "enforcement": "strict",
          "violation": "build_fail"
        },
        "animationLibraries": {
          "allowed": ["Ant Motion"],
          "forbidden": ["CSS 动画"],
          "enforcement": "strict",
          "violation": "build_fail"
        },
        "codeQuality": {
          "typescript": {
            "strictMode": true,
            "noAnyType": true,
            "enforcement": "error"
          },
          "maxFileLines": 300,
          "maxFunctionLines": 40,
          "minimalChanges": {
            "maxLines": 50,
            "principle": "最小变更原则"
          }
        },
        "apiStandards": {
          "responseFormat": {
            "required": ["code", "data", "message", "timestamp"],
            "template": {
              "code": 200,
              "data": {},
              "message": "success",
              "timestamp": "${timestamp}"
            }
          },
          "security": {
            "noDirectAxios": true,
            "useSecurityService": true,
            "enforcement": "strict",
            "violation": "security_block"
          }
        },
        "databaseStandards": {
          "transactionRequired": true,
          "forbiddenOperations": ["DROP", "TRUNCATE", "ALTER"],
          "enforcement": "strict",
          "violation": "terminate"
        },
        "styleStandards": {
          "cssModules": true,
          "forbiddenStyles": ["行内样式", "全局选择器"],
          "enforcement": "strict"
        }
      },

      "agentConfiguration": {
        "roleId": "TRAE-ALYR-DYNAMIC",
        "version": "V4.2.3",
        "effectiveDate": new Date().toISOString().split('T')[0],
        "projectScope": "多语言框架项目专属",
        "languages": {
          "conversation": "简体中文",
          "code": "中英混合",
          "comments": "中文"
        },
        "behaviorRules": {
          "deepThinking": true,
          "readSpecifications": true,
          "noCreativity": true,
          "noTechDiscussion": true
        },
        "commands": {
          "aiCheck": "npm run ai:check",
          "aiValidate": "npm run ai:validate",
          "aiFix": "npm run ai:fix",
          "quickInstall": "npm run quick:install",
          "smartInstall": "npm run smart:install",
          "healthCheck": "npm run health:check",
          "aiMonitor": "npm run ai:monitor"
        }
      },

      "violationMatrix": {
        "priorities": {
          "P0": {
            "type": "安全规则",
            "timing": "实时监控",
            "consequence": "立即终止",
            "examples": ["高危SQL检测"]
          },
          "P1": {
            "type": "文件命名",
            "timing": "文件创建时",
            "consequence": "自动删除",
            "examples": ["多语言文件检测"]
          },
          "P2": {
            "type": "版权声明",
            "timing": "Git提交时",
            "consequence": "阻塞提交",
            "examples": ["自动版权修复"]
          },
          "P3": {
            "type": "组件规范",
            "timing": "编译时",
            "consequence": "构建失败",
            "examples": ["ProComponents强制"]
          },
          "P4": {
            "type": "代码质量",
            "timing": "代码审查时",
            "consequence": "警告提示",
            "examples": ["智能依赖检查"]
          },
          "P5": {
            "type": "多语言支持",
            "timing": "环境检测时",
            "consequence": "自动安装",
            "examples": ["10种语言支持"]
          }
        },
        "autoProcessing": {
          "后端文件无前缀": {
            "action": "立即删除",
            "level": "特级",
            "icon": "🔥"
          },
          "后端缺少版权": {
            "action": "阻塞提交",
            "level": "一级",
            "icon": "🚫"
          },
          "使用非ProComponents": {
            "action": "编译失败",
            "level": "二级",
            "icon": "❌"
          },
          "使用any类型": {
            "action": "类型检查失败",
            "level": "一级",
            "icon": "⚠️"
          },
          "直接调用axios": {
            "action": "安全扫描拦截",
            "level": "三级",
            "icon": "🛡️"
          },
          "使用Echarts图表": {
            "action": "构建失败",
            "level": "二级",
            "icon": "🚫"
          },
          "高危SQL操作": {
            "action": "立即终止",
            "level": "特级",
            "icon": "🔥"
          },
          "跳过事务管理": {
            "action": "数据库警告",
            "level": "二级",
            "icon": "⚠️"
          }
        }
      },

      "i18n": {
        "defaultLanguage": "zh-CN",
        "supportedLanguages": ["zh-CN", "en-US", "ja-JP"],
        "autoDetect": true,
        "fallback": "zh-CN"
      },

      "features": {
        "codeGeneration": true,
        "realTimeMonitoring": true,
        "autoFix": true,
        "multiLanguageSupport": true,
        "smartInstall": true,
        "healthCheck": true
      }
    };
  }

  /**
   * 确保备份目录存在
   */
  ensureBackupDir() {
    if (!fs.existsSync(this.backupDir)) {
      fs.mkdirSync(this.backupDir, { recursive: true });
    }
  }

  /**
   * 保存配置
   */
  saveConfig() {
    try {
      this.config.meta.lastUpdated = new Date().toISOString();
      fs.writeFileSync(this.configPath, JSON.stringify(this.config, null, 2), 'utf8');
      console.log(chalk.green('✅ 统一配置已保存'));
      return true;
    } catch (error) {
      console.log(chalk.red(`❌ 配置保存失败: ${error.message}`));
      return false;
    }
  }

  /**
   * 创建备份
   */
  createBackup() {
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const backupPath = path.join(this.backupDir, `config-backup-${timestamp}.json`);
    
    try {
      fs.writeFileSync(backupPath, JSON.stringify(this.config, null, 2), 'utf8');
      console.log(chalk.blue(`📦 配置备份已创建: ${backupPath}`));
      return backupPath;
    } catch (error) {
      console.log(chalk.red(`❌ 备份创建失败: ${error.message}`));
      return null;
    }
  }

  /**
   * 同步到所有目标文件
   */
  async syncToAllFiles() {
    console.log(chalk.blue('🔄 开始同步配置到所有文件...'));
    
    // 创建备份
    this.createBackup();
    
    const results = [];
    
    for (const targetFile of this.targetFiles) {
      try {
        const result = await this.syncToFile(targetFile);
        results.push(result);
      } catch (error) {
        console.log(chalk.red(`❌ 同步失败 ${targetFile}: ${error.message}`));
        results.push({ file: targetFile, success: false, error: error.message });
      }
    }
    
    // 输出同步结果
    console.log(chalk.green('\n📊 同步结果汇总:'));
    results.forEach(result => {
      if (result.success) {
        console.log(chalk.green(`  ✅ ${result.file}`));
      } else {
        console.log(chalk.red(`  ❌ ${result.file}: ${result.error}`));
      }
    });
    
    return results;
  }

  /**
   * 同步到指定文件
   */
  async syncToFile(targetFile) {
    const filePath = path.resolve(__dirname, targetFile);
    
    if (!fs.existsSync(filePath)) {
      throw new Error(`目标文件不存在: ${filePath}`);
    }
    
    const fileName = path.basename(targetFile);
    const fileExt = path.extname(targetFile);
    
    switch (fileName) {
      // JSON 配置文件
      case 'tech-stack-config.json':
        return this.syncToTechStackConfig(filePath);
      case 'package.json':
        return this.syncToPackageJson(filePath);
      case 'package-lock.json':
        return this.syncToPackageLockJson(filePath);
      case 'directory-structure.json':
        return this.syncToDirectoryStructure(filePath);
      case 'startup-report.json':
        return this.syncToStartupReport(filePath);
      
      // JavaScript 文件
      case 'multi-framework-adapter.js':
        return this.syncToMultiFrameworkAdapter(filePath);
      case 'smart-install.js':
        return this.syncToSmartInstall(filePath);
      case 'start.js':
        return this.syncToJavaScriptFile(filePath, 'start');
      case 'version-info.js':
        return this.syncToJavaScriptFile(filePath, 'version-info');
      case 'auto-setup.js':
        return this.syncToJavaScriptFile(filePath, 'auto-setup');
      case 'ai-bootstrap.js':
        return this.syncToJavaScriptFile(filePath, 'ai-bootstrap');
      case 'unified-config-cli.js':
        return this.syncToJavaScriptFile(filePath, 'unified-config-cli');
      case 'multi-tech-demo.js':
        return this.syncToJavaScriptFile(filePath, 'multi-tech-demo');
      case 'code-generator-cli.js':
        return this.syncToJavaScriptFile(filePath, 'code-generator-cli');
      case 'system-health-check.js':
        return this.syncToJavaScriptFile(filePath, 'system-health-check');
      case 'real-time-monitor.js':
        return this.syncToJavaScriptFile(filePath, 'real-time-monitor');
      case 'fix-file.js':
        return this.syncToJavaScriptFile(filePath, 'fix-file');
      case 'ai-rules-checker.js':
        return this.syncToJavaScriptFile(filePath, 'ai-rules-checker');
      case 'config-sync.js':
        return this.syncToJavaScriptFile(filePath, 'config-sync');
      
      // PowerShell 脚本
      case 'auto-install.ps1':
        return this.syncToPowerShellScript(filePath, 'auto-install');
      case 'uninstall.ps1':
        return this.syncToPowerShellScript(filePath, 'uninstall');
      
      // Markdown 文档
      case 'multi-language-framework-support.md':
        return this.syncToMarkdownDoc(filePath, 'multi-language-framework-support');
      case 'UNIFIED-CONFIG-GUIDE.md':
        return this.syncToMarkdownDoc(filePath, 'unified-config-guide');
      case 'CONFIG-QUICK-START.md':
        return this.syncToMarkdownDoc(filePath, 'config-quick-start');
      case 'PROJECT-QUICK-START.md':
        return this.syncToMarkdownDoc(filePath, 'project-quick-start');
      case 'SMART-INSTALL-GUIDE.md':
        return this.syncToMarkdownDoc(filePath, 'smart-install-guide');
      case 'VERSION-UPDATE-SUMMARY.md':
        return this.syncToMarkdownDoc(filePath, 'version-update-summary');
      case 'README.md':
        return this.syncToMarkdownDoc(filePath, 'readme');
      case 'project_rules.md':
        return this.syncToMarkdownDoc(filePath, 'project-rules');
      case 'user_rules.md':
        return this.syncToMarkdownDoc(filePath, 'user-rules');
      case '智能体执行检查清单.md':
        return this.syncToAgentChecklist(filePath);
      
      // 其他文件
      case '.gitignore':
        return this.syncToGitignore(filePath);
      
      default:
        if (fileExt === '.md') {
          return this.syncToMarkdownDoc(filePath, 'generic');
        } else if (fileExt === '.js') {
          return this.syncToJavaScriptFile(filePath, 'generic');
        } else if (fileExt === '.json') {
          return this.syncToJsonFile(filePath, 'generic');
        }
        throw new Error(`不支持的文件类型: ${targetFile}`);
    }
  }

  /**
   * 同步到技术栈配置文件
   */
  syncToTechStackConfig(filePath) {
    try {
      const techConfig = {
        name: this.config.project.name + '-tech-stack-config',
        version: this.config.project.version,
        description: this.config.project.displayName + '多语言多框架技术栈配置文件',
        author: this.config.project.author,
        copyright: this.config.meta.copyright,
        supportedLanguages: this.config.languages,
        supportedFrameworks: this.config.frameworks,
        dependencies: this.config.dependencies,
        i18n: this.config.i18n,
        features: this.config.features
      };
      
      fs.writeFileSync(filePath, JSON.stringify(techConfig, null, 2), 'utf8');
      return { file: 'tech-stack-config.json', success: true };
    } catch (error) {
      throw new Error(`同步技术栈配置失败: ${error.message}`);
    }
  }

  /**
   * 同步到package.json
   */
  syncToPackageJson(filePath) {
    try {
      const packageJson = JSON.parse(fs.readFileSync(filePath, 'utf8'));
      
      // 更新基本信息
      packageJson.name = this.config.project.name;
      packageJson.version = this.config.project.version;
      packageJson.description = this.config.project.description;
      packageJson.author = this.config.project.author;
      packageJson.license = this.config.project.license;
      packageJson.homepage = this.config.project.homepage;
      packageJson.repository.url = this.config.project.repository;
      packageJson.engines.node = this.config.project.nodeVersion;
      
      fs.writeFileSync(filePath, JSON.stringify(packageJson, null, 2), 'utf8');
      return { file: 'package.json', success: true };
    } catch (error) {
      throw new Error(`同步package.json失败: ${error.message}`);
    }
  }

  /**
   * 同步到package-lock.json
   */
  syncToPackageLockJson(filePath) {
    try {
      const packageLockJson = JSON.parse(fs.readFileSync(filePath, 'utf8'));
      
      // 更新基本信息
      packageLockJson.name = this.config.project.name;
      packageLockJson.version = this.config.project.version;
      
      // 如果存在packages字段，也更新根包的信息
      if (packageLockJson.packages && packageLockJson.packages[""]) {
        packageLockJson.packages[""].name = this.config.project.name;
        packageLockJson.packages[""].version = this.config.project.version;
      }
      
      fs.writeFileSync(filePath, JSON.stringify(packageLockJson, null, 2), 'utf8');
      return { file: 'package-lock.json', success: true };
    } catch (error) {
      throw new Error(`同步package-lock.json失败: ${error.message}`);
    }
  }

  /**
   * 同步到目录结构配置
   */
  syncToDirectoryStructure(filePath) {
    try {
      const dirStructure = JSON.parse(fs.readFileSync(filePath, 'utf8'));
      
      // 更新基本信息
      dirStructure.projectName = this.config.project.displayName;
      dirStructure.version = this.config.project.version;
      dirStructure.lastUpdated = this.config.meta.lastUpdated.split('T')[0];
      
      fs.writeFileSync(filePath, JSON.stringify(dirStructure, null, 2), 'utf8');
      return { file: 'directory-structure.json', success: true };
    } catch (error) {
      throw new Error(`同步目录结构配置失败: ${error.message}`);
    }
  }

  /**
   * 同步到多框架适配器
   */
  syncToMultiFrameworkAdapter(filePath) {
    try {
      let content = fs.readFileSync(filePath, 'utf8');
      
      // 提取启用的语言和框架
      const enabledLanguages = [
        ...this.config.languages.frontend.filter(l => l.enabled).map(l => l.key),
        ...this.config.languages.backend.filter(l => l.enabled).map(l => l.key)
      ];
      
      const enabledFrameworks = {
        frontend: this.config.frameworks.frontend.filter(f => f.enabled).map(f => f.key),
        backend: this.config.frameworks.backend.filter(f => f.enabled).map(f => f.key),
        mobile: this.config.frameworks.mobile ? this.config.frameworks.mobile.filter(f => f.enabled).map(f => f.key) : []
      };
      
      // 替换supportedLanguages数组
      const languagesRegex = /this\.supportedLanguages\s*=\s*\[[\s\S]*?\];/;
      const languagesReplacement = `this.supportedLanguages = ${JSON.stringify(enabledLanguages, null, 6)};`;
      content = content.replace(languagesRegex, languagesReplacement);
      
      // 替换supportedFrameworks对象
      const frameworksRegex = /this\.supportedFrameworks\s*=\s*\{[\s\S]*?\};/;
      const frameworksReplacement = `this.supportedFrameworks = ${JSON.stringify(enabledFrameworks, null, 6)};`;
      content = content.replace(frameworksRegex, frameworksReplacement);
      
      fs.writeFileSync(filePath, content, 'utf8');
      return { file: 'multi-framework-adapter.js', success: true };
    } catch (error) {
      throw new Error(`同步多框架适配器失败: ${error.message}`);
    }
  }

  /**
   * 同步到智能安装器
   */
  syncToSmartInstall(filePath) {
    try {
      let content = fs.readFileSync(filePath, 'utf8');
      
      // 更新版本号 (支持所有4.2.x版本)
      content = content.replace(
        /(?<![.\d])[vV]?4\.2\.[0-9]+(?![.\d])/g,
        this.config.project.version
      );
      
      // 更新版本字符串
      content = content.replace(
        /版本[：:]\s*[vV]?4\.2\.[0-9]+/g,
        `版本: ${this.config.project.version}`
      );
      
      // 更新console.log中的版本号
      content = content.replace(
        /console\.log\([^)]*[vV]?4\.2\.[0-9]+[^)]*\)/g,
        (match) => match.replace(/[vV]?4\.2\.[0-9]+/, this.config.project.version)
      );
      
      // 更新项目名称
      content = content.replace(
        /Builder\.Alyr\.Net 智能多语言依赖自动安装器/g,
        this.config.project.displayName + ' 智能多语言依赖自动安装器'
      );
      
      // 替换supportedLanguages对象
      const dependenciesRegex = /this\.supportedLanguages\s*=\s*\{[\s\S]*?\};/;
      const dependenciesReplacement = `this.supportedLanguages = ${JSON.stringify(this.config.dependencies, null, 8)};`;
      content = content.replace(dependenciesRegex, dependenciesReplacement);
      
      fs.writeFileSync(filePath, content, 'utf8');
      return { file: 'smart-install.js', success: true };
    } catch (error) {
      throw new Error(`同步智能安装器失败: ${error.message}`);
    }
  }

  /**
   * 同步到 Markdown 文档
   */
  syncToMarkdownDoc(filePath, docType) {
    try {
      let content = fs.readFileSync(filePath, 'utf8');
      const fileName = path.basename(filePath);
      
      if (docType === 'multi-language-framework-support') {
        // 更新多语言框架支持文档
        content = this.updateMultiLanguageFrameworkDoc(content);
      } else {
        // 通用 Markdown 文档更新
        content = this.updateGenericMarkdownDoc(content);
      }
      
      fs.writeFileSync(filePath, content, 'utf8');
      return { file: fileName, success: true };
    } catch (error) {
      throw new Error(`同步Markdown文档失败: ${error.message}`);
    }
  }

  /**
   * 更新多语言框架支持文档
   */
  updateMultiLanguageFrameworkDoc(content) {
    // 更新版本信息 - 统一为V格式 (支持所有4.2.x版本)
   content = content.replace(
      /# Builder\.Alyr\.Net 多语言多框架支持方案 [vV]?4\.2\.[0-9]+/,
      `# Builder.Alyr.Net 多语言多框架支持方案 ${this.config.project.version}`
    );
    
    // 更新文档头部版本信息
    content = content.replace(
      /\*\*版本[：:]\s*[vV]?4\.2\.[0-9]+\*\*/g,
      `**版本：${this.config.project.version}**`
    );
    
    // 更新最后更新时间
    const updateDate = new Date(this.config.meta.lastUpdated).toISOString().split('T')[0];
    content = content.replace(
      /最后更新：\d{4}-\d{2}-\d{2}/,
      `最后更新：${updateDate}`
    );
    
    // 更新生效日期
    content = content.replace(
      /生效日期[：:]\s*\d{4}-\d{2}-\d{2}/g,
      `生效日期：${updateDate}`
    );
    
    // 更新支持的语言统计
    const frontendCount = this.config.languages.frontend.filter(l => l.enabled).length;
    const backendCount = this.config.languages.backend.filter(l => l.enabled).length;
    
    content = content.replace(
      /支持 \d+ 种前端语言/,
      `支持 ${frontendCount} 种前端语言`
    );
    
    content = content.replace(
      /支持 \d+ 种后端语言/,
      `支持 ${backendCount} 种后端语言`
    );
    
    // 更新安全监控要点
    if (this.config.security && this.config.security.monitoring_points) {
      const securitySection = this.generateSecurityMonitoringSection();
      content = content.replace(
        /### 10\.1 多语言安全适配[\s\S]*?(?=###|$)/,
        securitySection
      );
    }
    
    return content;
  }

  /**
   * 更新通用 Markdown 文档
   */
  updateGenericMarkdownDoc(content) {
    // 更新版本号 - 统一为V格式，更精确的匹配 (支持所有4.2.x版本)
    content = content.replace(
      /(?<![.\d])[vV]?4\.2\.[0-9]+(?![.\d])/g,
      this.config.project.version
    );
    
    // 更新 "版本：4.x" 格式
    content = content.replace(
      /版本[：:]\s*[vV]?4\.2\.[0-9]+/g,
      `版本：${this.config.project.version}`
    );
    
    // 更新 "**版本：4.x**" 格式
    content = content.replace(
      /\*\*版本[：:]\s*[vV]?4\.2\.[0-9]+\*\*/g,
      `**版本：${this.config.project.version}**`
    );
    
    // 更新 "**版本**: 4.x" 格式
    content = content.replace(
      /\*\*版本\*\*[：:]\s*[vV]?4\.2\.[0-9]+/g,
      `**版本**: ${this.config.project.version}`
    );
    
    // 更新JSON中的版本号
    content = content.replace(
      /"version":\s*"[vV]?4\.2\.[0-9]+"/g,
      `"version": "${this.config.project.version}"`
    );
    
    // 更新括号中的版本号，如 (V4.2.3)
    content = content.replace(
      /\([vV]?4\.2\.[0-9]+\)/g,
      `(${this.config.project.version})`
    );
    
    // 更新标题中的版本号
    content = content.replace(
      /# [^#\n]* [vV]?4\.2\.[0-9]+/g,
      (match) => match.replace(/[vV]?4\.2\.[0-9]+/, this.config.project.version)
    );
    
    // 更新日期
    const updateDate = new Date(this.config.meta.lastUpdated).toISOString().split('T')[0];
    content = content.replace(
      /\d{4}-\d{2}-\d{2}/g,
      updateDate
    );
    
    return content;
  }

  /**
   * 生成安全监控要点章节
   */
  generateSecurityMonitoringSection() {
    if (!this.config.security) return '';
    
    let section = '### 10.1 多语言安全适配\n\n';
    section += '```typescript\n';
    section += '// 安全适配器接口\n';
    section += 'interface ISecurityAdapter {\n';
    section += '  // 身份验证\n';
    section += '  authenticate(credentials: any): Promise<AuthResult>;\n';
    section += '  \n';
    section += '  // 权限验证\n';
    section += '  authorize(user: User, resource: string, action: string): Promise<boolean>;\n';
    section += '  \n';
    section += '  // 安全监控\n';
    section += '  monitor(event: SecurityEvent): void;\n';
    section += '}\n';
    section += '```\n\n';
    
    section += '#### 安全监控要点\n\n';
    this.config.security.monitoring_points.forEach((point, index) => {
      section += `${index + 1}. **${point}**\n`;
    });
    
    section += '\n#### 违规处理级别\n\n';
    section += '| 级别 | 处理方式 | 描述 |\n';
    section += '|------|----------|------|\n';
    
    Object.entries(this.config.security.violations.levels).forEach(([level, info]) => {
      section += `| ${level} | ${info.actions.join(', ')} | ${info.description} |\n`;
    });
    
    section += '\n';
    return section;
  }

  /**
   * 同步到启动报告配置
   */
  syncToStartupReport(filePath) {
    try {
      const startupReport = JSON.parse(fs.readFileSync(filePath, 'utf8'));
      
      // 更新基本信息
      startupReport.project = this.config.project.name;
      startupReport.version = this.config.project.version;
      startupReport.description = this.config.project.description;
      startupReport.author = this.config.project.author;
      startupReport.website = this.config.project.homepage;
      
      fs.writeFileSync(filePath, JSON.stringify(startupReport, null, 2), 'utf8');
      return { file: 'startup-report.json', success: true };
    } catch (error) {
      throw new Error(`同步启动报告配置失败: ${error.message}`);
    }
  }

  /**
   * 更新智能体执行检查清单文件
   */
  updateAgentChecklistFile(content) {
    const config = this.config;
    
    // 更新版本号 (支持所有4.2.x版本)
    content = content.replace(
      /(?<![.\d])[vV]?4\.2\.[0-9]+(?![.\d])/g,
      config.project.version
    );
    
    // 更新文件命名规则
    if (config.developmentStandards && config.developmentStandards.fileNaming) {
      const backendPrefix = config.developmentStandards.fileNaming.backend.prefix;
      const backendPattern = config.developmentStandards.fileNaming.backend.pattern;
      
      // 更新后端文件命名规则 - 支持多种前缀
      content = content.replace(
        /文件名必须: (Alyr-|Vue-|Ng-|Node-)\{PascalCase\}\.\{ext\}/g,
        `文件名必须: ${backendPattern}`
      );
      
      content = content.replace(
        /(Alyr-|Vue-|Ng-|Node-)\{PascalCase\}\.\{ext\}/g,
        backendPattern
      );
    }
    
    // 更新版权声明
    if (config.developmentStandards && config.developmentStandards.copyright) {
      const copyrightTemplate = config.developmentStandards.copyright.template;
      
      // 支持多种版权声明格式
      content = content.replace(
        /© 2020-2025 (ALYR\.NET|ANGULAR-TECH\.NET|NODE-TECH\.NET)/g,
        copyrightTemplate
      );
    }
    
    // 更新组件库规范
    if (config.developmentStandards && config.developmentStandards.componentLibraries) {
      const reactLib = config.developmentStandards.componentLibraries.react || 'ProComponents';
      const vueLib = config.developmentStandards.componentLibraries.vue || 'Element Plus';
      const angularLib = config.developmentStandards.componentLibraries.angular || 'Angular Material';
      
      content = content.replace(
        /使用 ProComponents 组件库/g,
        `使用 ${reactLib} 组件库`
      );
      
      content = content.replace(
        /ProComponents/g,
        reactLib
      );
      
      content = content.replace(
        /Element Plus/g,
        vueLib
      );
      
      content = content.replace(
        /Angular Material/g,
        angularLib
      );
    }
    
    // 更新图表库规范
    if (config.developmentStandards && config.developmentStandards.chartLibraries) {
      const allowedCharts = config.developmentStandards.chartLibraries.allowed.join(', ');
      const forbiddenCharts = config.developmentStandards.chartLibraries.forbidden.join(', ');
      
      content = content.replace(
        /图表使用 AntV\/G2Plot \(禁用 Echarts\)/g,
        `图表使用 ${allowedCharts} (禁用 ${forbiddenCharts})`
      );
    }
    
    // 更新动效库规范
    if (config.developmentStandards && config.developmentStandards.animationLibraries) {
      const allowedAnimations = config.developmentStandards.animationLibraries.allowed.join(', ');
      const forbiddenAnimations = config.developmentStandards.animationLibraries.forbidden.join(', ');
      
      content = content.replace(
        /动效使用 Ant Motion \(禁用 CSS 动画\)/g,
        `动效使用 ${allowedAnimations} (禁用 ${forbiddenAnimations})`
      );
    }
    
    // 更新代码质量规范
    if (config.developmentStandards && config.developmentStandards.codeQuality) {
      const maxFileLines = config.developmentStandards.codeQuality.maxFileLines;
      const maxFunctionLines = config.developmentStandards.codeQuality.maxFunctionLines;
      const maxChangeLines = config.developmentStandards.codeQuality.minimalChanges.maxLines;
      
      content = content.replace(
        /组件文件 ≤300 行，函数 ≤40 行/g,
        `组件文件 ≤${maxFileLines} 行，函数 ≤${maxFunctionLines} 行`
      );
      
      content = content.replace(
        /修改行数 ≤50/g,
        `修改行数 ≤${maxChangeLines}`
      );
    }
    
    // 更新数据库规范
    if (config.developmentStandards && config.developmentStandards.databaseStandards) {
      const forbiddenOps = config.developmentStandards.databaseStandards.forbiddenOperations.join(', ');
      
      content = content.replace(
        /禁止高危 SQL 操作 \(DROP, TRUNCATE, ALTER\)/g,
        `禁止高危 SQL 操作 (${forbiddenOps})`
      );
    }
    
    // 更新违规处理矩阵
    if (config.violationMatrix && config.violationMatrix.autoProcessing) {
      const violations = config.violationMatrix.autoProcessing;
      
      // 构建新的违规处理表格
      let violationTable = '| 违规类型 | 自动处理 | 严重等级 |\n';
      violationTable += '|---------|---------|----------|\n';
      
      Object.entries(violations).forEach(([violation, info]) => {
        violationTable += `| ${violation} | ${info.icon} ${info.action} | ${info.level} |\n`;
      });
      
      // 替换现有的违规处理表格
      content = content.replace(
        /\| 违规类型 \| 自动处理 \| 严重等级 \|[\s\S]*?(?=\n---|\n##|\n\*\*|$)/,
        violationTable
      );
    }
    
    // 更新智能体配置
    if (config.agentConfiguration) {
      const agentConfig = config.agentConfiguration;
      
      // 更新角色ID
      content = content.replace(
        /Builder.Alyr.Net/g,
        agentConfig.roleId
      );
      
      // 更新生效日期
      content = content.replace(
        /生效日期[：:]\s*\d{4}-\d{2}-\d{2}/g,
        `生效日期：${agentConfig.effectiveDate}`
      );
      
      // 更新命令
      if (agentConfig.commands) {
        Object.entries(agentConfig.commands).forEach(([key, command]) => {
          const commandPattern = new RegExp(`npm run ${key.replace(/([A-Z])/g, ':$1').toLowerCase().replace(/^:/, '')}`, 'g');
          content = content.replace(commandPattern, command);
        });
      }
    }
    
    // 更新优先级矩阵
    if (config.violationMatrix && config.violationMatrix.priorities) {
      const priorities = config.violationMatrix.priorities;
      
      // 构建新的优先级表格
      let priorityTable = '| 优先级 | 规则类型 | 执行时机 | 违规后果 | V4.2.3新增 |\n';
      priorityTable += '|-------|---------|---------|----------|----------|\n';
      
      Object.entries(priorities).forEach(([priority, info]) => {
        const examples = info.examples.join(', ');
        priorityTable += `| ${priority} | ${info.type} | ${info.timing} | ${info.consequence} | ${examples} |\n`;
      });
      
      // 替换现有的优先级表格
      content = content.replace(
        /\| 优先级 \| 规则类型 \| 执行时机 \| 违规后果 \| V4\.2\.0新增 \|[\s\S]*?(?=\n---|\n##|\n\*\*|$)/,
        priorityTable
      );
    }
    
    return content;
  }

  /**
   * 同步到智能体执行检查清单
   */
  syncToAgentChecklist(filePath) {
    try {
      let content = fs.readFileSync(filePath, 'utf8');
      content = this.updateAgentChecklistFile(content);
      fs.writeFileSync(filePath, content, 'utf8');
      return { file: '智能体执行检查清单.md', success: true };
    } catch (error) {
      throw new Error(`同步智能体执行检查清单失败: ${error.message}`);
    }
  }

  /**
   * 同步到JavaScript文件
   */
  syncToJavaScriptFile(filePath, fileType) {
    try {
      let content = fs.readFileSync(filePath, 'utf8');
      const fileName = path.basename(filePath);
      
      // 更新特定的版本号模式，避免过度替换 - 统一为V格式 (支持所有4.2.x版本)
      content = content.replace(
        /(?<![.\d])[vV]?4\.2\.[0-9]+(?![.\d])/g,
        this.config.project.version
      );
      
      // 更新版本字符串
      content = content.replace(
        /版本[：:]\s*[vV]?4\.2\.[0-9]+/g,
        `版本: ${this.config.project.version}`
      );
      
      // 更新this.version赋值
      content = content.replace(
        /this\.version\s*=\s*['"`][vV]?4\.2\.[0-9]+['"`]/g,
        `this.version = '${this.config.project.version}'`
      );
      
      // 更新console.log中的版本号
      content = content.replace(
        /console\.log\([^)]*[vV]?4\.2\.[0-9]+[^)]*\)/g,
        (match) => match.replace(/[vV]?4\.2\.[0-9]+/, this.config.project.version)
      );
      
      // 更新注释中的版本号
      content = content.replace(
        /\/\/ [^\\n]*[vV]?4\.2\.[0-9]+[^\\n]*/g,
        (match) => match.replace(/[vV]?4\.2\.[0-9]+/, this.config.project.version)
      );
      
      // 更新Builder.Alyr.Net项目名称
      content = content.replace(
        /Builder\.Alyr\.Net 智能体代码规范检测工具/g,
        this.config.project.displayName
      );
      
      // 更新网站链接
      content = content.replace(
        /https:\/\/builder\.alyr\.net/g,
        this.config.project.homepage
      );
      
      // 避免替换process.argv.slice等代码
      content = content.replace(
        /process\.argv(\d+\.\d+(?:\.\d+)?)slice/g,
        'process.argv.slice'
      );
      
      // 根据文件类型进行特定更新
      switch (fileType) {
        case 'version-info':
          content = this.updateVersionInfoFile(content);
          break;
        case 'auto-setup':
          content = this.updateAutoSetupFile(content);
          break;
        case 'ai-bootstrap':
          content = this.updateAiBootstrapFile(content);
          break;
        case 'unified-config-cli':
          content = this.updateUnifiedConfigCliFile(content);
          break;
        case 'start':
          content = this.updateStartFile(content);
          break;
      }
      
      fs.writeFileSync(filePath, content, 'utf8');
      return { file: fileName, success: true };
    } catch (error) {
      throw new Error(`同步JavaScript文件失败: ${error.message}`);
    }
  }

  /**
   * 同步到PowerShell脚本
   */
  syncToPowerShellScript(filePath, scriptType) {
    try {
      let content = fs.readFileSync(filePath, 'utf8');
      const fileName = path.basename(filePath);
      
      // 更新版本号 - 统一为V格式 (支持所有4.2.x版本)
      content = content.replace(
        /\$version\s*=\s*["'][vV]?4\.2\.[0-9]+["']/g,
        `$version = "${this.config.project.version}"`
      );
      
      // 更新版本字符串
      content = content.replace(
        /版本[：:]\s*[vV]?4\.2\.[0-9]+/g,
        `版本: ${this.config.project.version}`
      );
      
      // 更新Write-Host中的版本信息
      content = content.replace(
        /Write-Host\s+"[^"]*[vV]?4\.2\.[0-9]+[^"]*"/g,
        (match) => {
          return match.replace(/[vV]?4\.2\.[0-9]+/, this.config.project.version);
        }
      );
      
      // 更新项目名称
      content = content.replace(
        /Builder\.Alyr\.Net 智能体代码规范检测工具/g,
        this.config.project.displayName
      );
      
      // 更新网站链接
      content = content.replace(
        /https:\/\/builder\.alyr\.net/g,
        this.config.project.homepage
      );
      
      fs.writeFileSync(filePath, content, 'utf8');
      return { file: fileName, success: true };
    } catch (error) {
      throw new Error(`同步PowerShell脚本失败: ${error.message}`);
    }
  }

  /**
   * 同步到.gitignore文件
   */
  syncToGitignore(filePath) {
    try {
      let content = fs.readFileSync(filePath, 'utf8');
      
      // 更新版本号 (支持所有V4.2.x版本)
      content = content.replace(
        /版本[：:]\s*[vV]?4\.2\.[0-9]+/g,
        `版本：${this.config.project.version}`
      );
      
      // 更新项目名称
      content = content.replace(
        /Builder\.Alyr\.Net 智能体代码规范检测工具/g,
        this.config.project.displayName
      );
      
      // 更新日期 - 支持多种日期格式
      const updateDate = new Date(this.config.meta.lastUpdated);
      const year = updateDate.getFullYear();
      const month = updateDate.getMonth() + 1;
      const day = updateDate.getDate();
      const chineseDateStr = `${year}年${month}月${day}日`;
      
      // 更新中文日期格式
      content = content.replace(
        /更新时间[：:]\s*\d{4}年\d{1,2}月\d{1,2}日/g,
        `更新时间：${chineseDateStr}`
      );
      
      // 更新ISO日期格式
      const isoDateStr = updateDate.toISOString().split('T')[0];
      content = content.replace(
        /更新时间[：:]\s*\d{4}-\d{2}-\d{2}/g,
        `更新时间：${chineseDateStr}`
      );
      
      fs.writeFileSync(filePath, content, 'utf8');
      return { file: '.gitignore', success: true };
    } catch (error) {
      throw new Error(`同步.gitignore文件失败: ${error.message}`);
    }
  }

  /**
   * 同步到通用JSON文件
   */
  syncToJsonFile(filePath, fileType) {
    try {
      const jsonData = JSON.parse(fs.readFileSync(filePath, 'utf8'));
      const fileName = path.basename(filePath);
      
      // 递归更新所有版本号字段
      this.updateVersionInObject(jsonData);
      
      // 通用字段更新
      if (jsonData.name) {
        jsonData.name = this.config.project.name;
      }
      if (jsonData.description) {
        jsonData.description = this.config.project.description;
      }
      
      fs.writeFileSync(filePath, JSON.stringify(jsonData, null, 2), 'utf8');
      return { file: fileName, success: true };
    } catch (error) {
      throw new Error(`同步JSON文件失败: ${error.message}`);
    }
  }

  /**
   * 递归更新对象中的所有版本号字段
   */
  updateVersionInObject(obj) {
    if (typeof obj !== 'object' || obj === null) {
      return;
    }
    
    for (const key in obj) {
      if (key === 'version' && typeof obj[key] === 'string') {
        // 如果是版本字段且匹配4.2.x格式，则更新
        if (/^[vV]?4\.2\.[0-9]+$/.test(obj[key])) {
          obj[key] = this.config.project.version;
        }
      } else if (typeof obj[key] === 'object') {
        // 递归处理嵌套对象
        this.updateVersionInObject(obj[key]);
      }
    }
  }

  /**
   * 更新version-info.js文件
   */
  updateVersionInfoFile(content) {
    // 更新版本号
    content = content.replace(
      /this\.version\s*=\s*['"`][vV]?[\d.]+['"`]/g,
      `this.version = '${this.config.project.version}'`
    );
    
    // 更新网站信息
    content = content.replace(
      /website:\s*['"`][^'"`]*['"`]/g,
      `website: '${this.config.project.homepage}'`
    );
    
    return content;
  }

  /**
   * 更新auto-setup.js文件
   */
  updateAutoSetupFile(content) {
    // 更新项目名称显示
    content = content.replace(
      /项目:\s*\${this\.packageJson\.name}/g,
      `项目: ${this.config.project.displayName}`
    );
    
    return content;
  }

  /**
   * 更新ai-bootstrap.js文件
   */
  updateAiBootstrapFile(content) {
    // 更新启动信息
    content = content.replace(
      /Builder\.Alyr\.Net 智能体启动成功！[vV]?[\d.]+/g,
      `Builder.Alyr.Net 智能体启动成功！${this.config.project.version}`
    );
    
    return content;
  }

  /**
   * 更新unified-config-cli.js文件
   */
  updateUnifiedConfigCliFile(content) {
    // 更新CLI标题
    content = content.replace(
      /Builder\.Alyr\.Net 统一配置管理器 [vV]?[\d.]+/g,
      `Builder.Alyr.Net 统一配置管理器 ${this.config.project.version}`
    );
    
    return content;
  }

  /**
   * 更新start.js文件
   */
  updateStartFile(content) {
    // 更新启动信息
    content = content.replace(
      /Builder\.Alyr\.Net 智能体代码规范检测工具 Trae 版 [vV]?[\d.]+/g,
      `Builder.Alyr.Net 智能体代码规范检测工具 Trae 版 ${this.config.project.version}`
    );
    
    return content;
  }

  /**
   * 获取配置摘要
   */
  getConfigSummary() {
    const enabledFrontendLangs = this.config.languages.frontend.filter(l => l.enabled).length;
    const enabledBackendLangs = this.config.languages.backend.filter(l => l.enabled).length;
    const enabledFrontendFrameworks = this.config.frameworks.frontend.filter(f => f.enabled).length;
    const enabledBackendFrameworks = this.config.frameworks.backend.filter(f => f.enabled).length;
    
    return {
      project: this.config.project.displayName,
      version: this.config.project.version,
      languages: {
        frontend: enabledFrontendLangs,
        backend: enabledBackendLangs,
        total: enabledFrontendLangs + enabledBackendLangs
      },
      frameworks: {
        frontend: enabledFrontendFrameworks,
        backend: enabledBackendFrameworks,
        total: enabledFrontendFrameworks + enabledBackendFrameworks
      },
      features: Object.keys(this.config.features).filter(key => this.config.features[key]).length,
      lastUpdated: this.config.meta.lastUpdated
    };
  }
}

module.exports = UnifiedConfigManager;

// 如果直接运行此脚本，则执行同步操作
if (require.main === module) {
  async function main() {
    try {
      console.log(chalk.blue('🚀 开始执行统一配置同步...'));
      
      const manager = new UnifiedConfigManager();
      const results = await manager.syncToAllFiles();
      
      console.log(chalk.green('\n✅ 配置同步完成！'));
      console.log(chalk.cyan('📊 同步结果统计:'));
      
      const successCount = results.filter(r => r.success).length;
      const failureCount = results.filter(r => !r.success).length;
      
      console.log(chalk.green(`  ✅ 成功: ${successCount} 个文件`));
      if (failureCount > 0) {
        console.log(chalk.red(`  ❌ 失败: ${failureCount} 个文件`));
        
        const failures = results.filter(r => !r.success);
        failures.forEach(failure => {
          console.log(chalk.red(`    - ${failure.file}: ${failure.error}`));
        });
      }
      
      // 显示配置摘要
      const summary = manager.getConfigSummary();
      console.log(chalk.cyan('\n📋 配置摘要:'));
      console.log(chalk.white(`  项目: ${summary.project}`));
      console.log(chalk.white(`  版本: ${summary.version}`));
      console.log(chalk.white(`  支持语言: ${summary.languages.total} 种 (前端: ${summary.languages.frontend}, 后端: ${summary.languages.backend})`));
      console.log(chalk.white(`  支持框架: ${summary.frameworks.total} 种 (前端: ${summary.frameworks.frontend}, 后端: ${summary.frameworks.backend})`));
      console.log(chalk.white(`  启用功能: ${summary.features} 项`));
      console.log(chalk.white(`  最后更新: ${summary.lastUpdated}`));
      
    } catch (error) {
      console.error(chalk.red('❌ 配置同步失败:'), error.message);
      process.exit(1);
    }
  }
  
  main();
}